#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

#include "../System/iniparser.h"
#include "Log.h"

char *buildFormat(const char* str1, const char* str2) {
    char *formatBuffer = malloc(strlen(str1) * sizeof(char) + strlen(str2) * sizeof(char) + strlen(": \n") * sizeof(char)+1);
    sprintf(formatBuffer, "%s: %s\n", str1, str2 );
    return formatBuffer;
}

int logHiddenError;
int logHiddenWarning;
int logHiddenDebug;
int logHiddenInformation;

void logInit()
{
    dictionary  *ini;

    /* Lade Config */
    ini = iniparser_load("Config.ini");
    if (ini==NULL) {
        logError("cannot parse file");
        return -1;
    }

    /* Lade die Werte */
    logHiddenError = iniparser_getint(ini, "log:error", 1);
    logHiddenWarning = iniparser_getint(ini, "log:warning", 1);
    logHiddenDebug = iniparser_getint(ini, "log:debug", 1);
    logHiddenInformation = iniparser_getint(ini, "log:information", 1);

    /* Schließen */
    iniparser_freedict(ini);
}

int logDebug( const char *format, ...) {
    /* Verstecken? */
    if(logHiddenDebug)
        return 1;

    va_list arg;
    int done;

    char *formatBuffer = buildFormat("Debug", format);

    va_start(arg, format);
    done = vfprintf(stdout, formatBuffer, arg);
    va_end(arg);

    free(formatBuffer);

    return done;
}

int logWarning(const char *format, ...) {
    /* Verstecken? */
    if(logHiddenWarning)
        return 1;

    va_list arg;
    int done;

    char *formatBuffer = buildFormat("Warning", format);

    va_start(arg, format);
    done = vfprintf(stdout, formatBuffer, arg);
    va_end(arg);

    free(formatBuffer);

    return done;
}

int logError(const char *format, ...) {
    /* Verstecken? */
    if(logHiddenError)
        return 1;

    va_list arg;
    int done;

    char *formatBuffer = buildFormat("Error", format);

    va_start(arg, format);
    done = vfprintf(stdout, formatBuffer, arg);
    va_end(arg);

    free(formatBuffer);

    return done;
}

int logInformation(const char *format, ...) {
    /* Verstecken? */
    if(logHiddenInformation)
        return 1;

    va_list arg;
    int done;

    char *formatBuffer = buildFormat("Information", format);

    va_start(arg, format);
    done = vfprintf(stdout, formatBuffer, arg);
    va_end(arg);

    free(formatBuffer);

    return done;
}
